using System;
using MSSystem = System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;

using Toenda.Rails.Data;
using Toenda.Rails.System;
using Toenda.Rails.DataContainer;
using Toenda.TFL.Drawing;

public partial class Controls_Main_ctrl_upload : UserControlBaseClass {
	private AccountProvider ap = new AccountProvider();
	private ImageProvider ip = new ImageProvider();
	private ImageGenerator ig = new ImageGenerator();
	private StaticProvider sp = new StaticProvider();
	private ServerPath serverpath = new ServerPath();

	/// <summary>
	/// Page_Load
	/// </summary>
	/// <param name="sender"></param>
	/// <param name="e"></param>
	protected void Page_Load(object sender, EventArgs e) {
		if(!IsPostBack) {
			plcUpload.Visible = true;

			bool canUpload = false;
			//double u = 0.0;

			Account acc = ap.GetAccount(Session["ZapprUserId"].ToString());

			//if(acc.Type == 0) {
			//    u = ap.GetUsersUploadedMB(acc.ID);

			//    if(u < Convert.ToDouble(acc.MaxStorageMB)) {
			//        canUpload = true;
			//    }
			//    else {
			//        canUpload = false;
			//    }
			//}
			//else {
			canUpload = true;
			plcLicence.Visible = true;

			ArrayList arr = sp.GetStaticItems("L001");

			rblUpgrade.DataSource = arr;
			rblUpgrade.DataValueField = "Value";
			rblUpgrade.DataTextField = "Content";
			rblUpgrade.DataBind();
			rblUpgrade.Items.Insert(0, new ListItem(GetLocalResourceObject("NoLicence").ToString(), "--"));

			rblUpgrade.SelectedIndex = 0;
			//}

			//if(!canUpload) {
			btnUpload.Enabled = false;
			//}
		}
	}

	/// <summary>
	/// btnUpload_Click
	/// </summary>
	/// <param name="sender"></param>
	/// <param name="e"></param>
	protected void btnUpload_Click(object sender, EventArgs e) {
		string fileExt = "";
		string image_guid = "";
		string temp_filename = "";
		string imgs_filename = "";
		string imgs_path = "";
		int i = 0;
		bool canUpload = false;
		double u = 0.0;
		string img_1024 = "";
		string img_500 = "";
		string img_240 = "";
		string img_100 = "";
		string img_75 = "";

		Account acc = ap.GetAccount(Session["ZapprUserId"].ToString());

		// file 1
		if(fu1.HasFile) {
			// check if user can upload
			u = ap.GetUsersUploadedMB(acc.ID);

			//if(u < Convert.ToDouble(acc.MaxStorageMB)) {
			//    canUpload = true;
			//}
			//else {
			//    canUpload = false;
			//}

			canUpload = true;

			//if(acc.Type == 0 && canUpload) {
			//    FileInfo fi = new FileInfo(fu1.FileName);
			//    long len = (fi.Length / 1024) / 1024;

			//    if(len > 5) {
			//        canUpload = false;
			//    }
			//}

			//if(canUpload) {
			fileExt = Path.GetExtension(fu1.FileName).ToLower();

			if(fileExt == ".jpg"
			|| fileExt == ".jpeg"
			|| fileExt == ".png"
			|| fileExt == ".bmp"
			|| fileExt == ".gif"
			|| fileExt == ".tiff") {
				try {
					image_guid = Guid.NewGuid().ToString();

					// temp upload
					imgs_path = serverpath.Path + @"\Images\";
					imgs_filename = imgs_path  + image_guid + "_org" + fileExt;

					temp_filename = serverpath.Path + @"\Temp\"
						+ image_guid + "_org" + fileExt;

					fu1.SaveAs(temp_filename);

					ExifReader ew = new ExifReader(temp_filename);
					string e_maker = ew.EquipmentMaker;
					string e_model = ew.EquipmentModel;
					ew = null;

					FileInfo tmpfile = new FileInfo(temp_filename);

					long len = (tmpfile.Length / 1024) / 1024;

					if(len < 5) {
						// generate images
						Bitmap imageOrg = new Bitmap(temp_filename);
						Bitmap image1024 = ig.Generate1024Pixel((Bitmap)imageOrg.Clone());
						Bitmap image500 = ig.Generate500Pixel((Bitmap)imageOrg.Clone());
						Bitmap image240 = ig.Generate240Pixel((Bitmap)imageOrg.Clone());
						Bitmap image100 = ig.Generate100Pixel((Bitmap)imageOrg.Clone());
						Bitmap image75 = ig.Generate75x75Pixel((Bitmap)imageOrg.Clone());

						// save in database
						ImageItem item1 = new ImageItem();
						item1.ID = Guid.NewGuid().ToString();
						item1.Access = (rbPrivate.Checked ? 1 : 0);
						//item1.Name = fu1.FileName;
						item1.Name = Path.GetFileNameWithoutExtension(fu1.FileName);
						item1.Description = "";
						item1.EquipmentMaker = e_maker;
						item1.EquipmentModel = e_model;

						if(acc.Type != 0) {
							item1.Licence = rblUpgrade.SelectedValue;
						}

						item1.ImageOriginal = image_guid + "_org" + fileExt;

						if(image1024 != null) {
							img_1024 = Guid.NewGuid().ToString();
							item1.Image1024 = img_1024 + "_1024.jpg";
						}

						if(image500 != null) {
							img_500 = Guid.NewGuid().ToString();
							item1.Image500 = img_500 + "_500.jpg";
						}

						if(image240 != null) {
							img_240 = Guid.NewGuid().ToString();
							item1.Image240 = img_240 + "_240.jpg";
						}

						if(image100 != null) {
							img_100 = Guid.NewGuid().ToString();
							item1.Image100 = img_100 + "_100.jpg";
						}

						if(image75 != null) {
							img_75 = Guid.NewGuid().ToString();
							item1.Image75x75 = img_75 + "_75x75.jpg";
						}

						item1.UserID = acc.ID;
						item1.UploadDate = DateTime.Now;
						item1.Type = 1;

						if(txtTags.Text.Trim() != "") {
							string[] tags = txtTags.Text.Split(new char[] { ',', ' ' });

							for(i = 0; i < tags.Length; i++) {
								if(tags[i].Trim() != "") {
									TagItem tag = new TagItem();
									tag.ID = Guid.NewGuid().ToString();
									tag.Tag = tags[i];

									item1.Tags.Add(tag);
								}
							}
						}
						// ---

						// upload
						tmpfile.CopyTo(imgs_filename, false);
						//imageOrg.Save(imgs_filename, ImageFormat.Jpeg);

						imgs_filename = imgs_filename.Replace("_org" + fileExt, "");

						if(image1024 != null) {
							image1024.Save(imgs_path + img_1024 + "_1024.jpg", ImageFormat.Jpeg);
							image1024.Dispose();
						}

						if(image500 != null) {
							image500.Save(imgs_path + img_500 + "_500.jpg", ImageFormat.Jpeg);
							image500.Dispose();
						}

						if(image240 != null) {
							image240.Save(imgs_path + img_240 + "_240.jpg", ImageFormat.Jpeg);
							image240.Dispose();
						}

						if(image100 != null) {
							image100.Save(imgs_path + img_100 + "_100.jpg", ImageFormat.Jpeg);
							image100.Dispose();
						}

						if(image75 != null) {
							image75.Save(imgs_path + img_75 + "_75x75.jpg", ImageFormat.Jpeg);
							image75.Dispose();
						}

						// count max upload mb
						double size = Convert.ToDouble(tmpfile.Length);
						size = size / 1024;
						size = size / 1024;

						size = Math.Round(size, 3);

						ap.CountUserUploadedMB(acc.ID, size);

						// dispose the original image
						// and save the image item
						// and finaly delete temp image
						imageOrg.Dispose();
						ip.SaveImage(item1);
						tmpfile.Delete();

						// re/generate badge
						BadgeSettings bs = ip.GetBadgeSetting(acc.ID);

						if(bs != null && bs.ID != "") {
							string code = ip.GenerateZapprBadge(
								bs,
								serverpath.Path + @"\Badges\",
								serverpath.Path + @"\Images\"
							);
						}

						// finish
						//Response.Redirect("default.aspx?id=images&user=" + acc.Username);
						Response.Redirect("~/images/" + acc.Username + "/default.aspx");
					}
					else {
						// to big file
						tmpfile.Delete();

						plcError.Visible = true;
						plcUpload.Visible = false;
						lblError.Text = GetLocalResourceObject("ErrorOn").ToString()
							+ " " + fu1.FileName 
							+ "<br />"
							+ GetLocalResourceObject("ErrorBigFile").ToString();
					}
				}
				catch(Exception ex) {
					plcError.Visible = true;
					plcUpload.Visible = false;
					lblError.Text = GetLocalResourceObject("Error").ToString();
					lblError.Text += ": " + ex.Message.ToString();
					//lblError.Text += "<br />";
					//lblError.Text += ex.StackTrace;

					Response.Redirect("~/images/" + acc.Username + "/default.aspx");
				}
			}
			else {
				plcError.Visible = true;
				plcUpload.Visible = false;
				lblError.Text = GetLocalResourceObject("ErrorOn").ToString()
					+ " " + fu1.FileName
					+ "<br />"
					+ GetLocalResourceObject("ErrorFileExt").ToString();
			}
			//}
			//else {
			//    return;
			//}
		}
		else {
			return;
		}
	}
}
